package com.vehicle.biz.eventListener;

import com.vehicle.biz.event.VehicleChangeEvent;
import com.vehicle.constants.Constants;
import com.vehicle.domains.dto.BaseResponse;
import com.vehicle.domains.entity.CommonVehicleEntity;
import com.vehicle.domains.entity.TransportVehicleEntity;
import com.vehicle.enums.GovUploadStatus;
import com.vehicle.enums.VehicleTypeEnum;
import com.vehicle.exception.VehicleAccessException;
import com.vehicle.service.CommonVehicleService;
import com.vehicle.service.TransportVehicleService;
import com.vehicle.service.remote.TjRemoteService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class VehicleChangeUploadGovListener implements ApplicationListener<VehicleChangeEvent> {
    @Resource
    private TjRemoteService tjRemoteService;
    @Resource
    private CommonVehicleService commonVehicleService;
    @Resource
    private TransportVehicleService transportVehicleService;
    @Override
    public void onApplicationEvent(VehicleChangeEvent event) {
        Long id = event.getId();

        CommonVehicleEntity commonVehicleEntity = commonVehicleService.getCommonVehicleById(id);
        if (commonVehicleEntity == null) {
            throw VehicleAccessException.DATA_NOT_EXIST.newInstance("普通车辆不存在");
        }

        if (!VehicleTypeEnum.TRANSPORT.name().equals(commonVehicleEntity.getVehicleType())) {
            return;
        }

        TransportVehicleEntity transportVehicleEntity = transportVehicleService.getTransportVehicleById(commonVehicleEntity.getAssociationId());
        if (transportVehicleEntity == null) {
            throw VehicleAccessException.DATA_NOT_EXIST.newInstance("运输车辆不存在");
        }

        TransportVehicleEntity updateTransportVehicleEntity = new TransportVehicleEntity();
        updateTransportVehicleEntity.setId(transportVehicleEntity.getId());

        try {
            BaseResponse baseResponse = tjRemoteService.putRegisterVehicleInfo(commonVehicleEntity, transportVehicleEntity);
            if (baseResponse != null && Constants.GOV_SUCCESS_CODE.equals(baseResponse.getCode())) {
                updateTransportVehicleEntity.setGovUploadStatus(GovUploadStatus.SUCCESS.name());
            } else {
                updateTransportVehicleEntity.setGovUploadStatus(GovUploadStatus.FAIL.name());
            }
        } catch (IOException e) {
            log.error("上报车辆注册信息至天津接口异常", e);
            updateTransportVehicleEntity.setGovUploadStatus(GovUploadStatus.FAIL.name());
        }

        transportVehicleService.updateTransportVehicle(updateTransportVehicleEntity);

    }
}
